﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;
using Coralcode.Adapter.File.Utils;
using Coralcode.Adapter.Javascript.FineUploader.Models;
using Coralcode.Adapter.Javascript.FineUploader.Utils;
using Coralcode.Base.Client.Enums;
using Coralcode.Base.Entity;
using Coralcode.MvcBase.Client.Controllers;
using CoralNode.CoralFile.Entity.Domains;
using CoralNode.Core.Entity.Domains.Node;
using CoralNode.Core.Entity.Domains.User;
using CoralNode.Core.Entity.Enums;
using CoralNode.Core.Entity.Model;
using CoralNode.Core.Entity.SearchQuerys.Node;
using CoralNode.Core.Entity.SearchQuerys.User;
using CoralNode.Core.IService.Node;
using CoralNode.Core.IService.Prototype;
using CoralNode.Core.IService.User;
using CoralNode.MvcClient.Contexts;
using CoralNode.MvcClient.Controllers;
using CoralNode.MvcClient.Helper;
using CoralNode.MvcClient.Models;
using Newtonsoft.Json;


namespace Gongfu.Controllers
{
    public class WorkNodeController :MvcControllerBase
    {
        private readonly INodeAccessService _nodeAccessService;
        private readonly IPrototypeAccessService _prototypeAccessService;
        private readonly INodeManageService _nodeService;
        private readonly IUserService _userService;
        private readonly IUserAccessService _userAccessService;

        public WorkNodeController(INodeAccessService nodeAccessService, IPrototypeAccessService prototypeAccessService,INodeManageService nodeManageService,IUserService userService,IUserAccessService userAccessService)
        {
            _nodeAccessService = nodeAccessService;
            _prototypeAccessService = prototypeAccessService;
            _nodeService = nodeManageService;
            _userService = userService;
            _userAccessService = userAccessService;
        }
        [HttpPost]
        public JsonResult WorkList(string key)
        {
            NodeDomain node =new NodeDomain();
            NodeSearchQuery query = new NodeSearchQuery()
            {
                Title = key
            };
            IList<NodeDomain> list = _nodeService.ListNode(query);
            if (list.Count > 0)
            {
                node = list.First();
            }
            var nodeModel = new NodeModel(node);
            return Json(nodeModel);
        }
        //随机数
        public string Code()
        {
            Random rd = new Random();
            int num = rd.Next(1000, 10000);
            return num.ToString();
        }
        //上传图片
        public void Upload()
        {
            if (Request.Files.Count > 0)
            {
                string code = Code();
                string time = DateTime.Now.ToFileTime().ToString();
                string nfname =code + time + Request.Files[0].FileName;
                string path = AppDomain.CurrentDomain.BaseDirectory + "uploads\\";
                string nsave = System.IO.Path.Combine(path, nfname);
                Request.Files[0].SaveAs(nsave);
                //返回文件路径
                Response.Write("<script type='text/javascript'>parent.upcallback('/uploads/" + nfname + "')</script>");
            }
        }
        [HttpPost]
        public ActionResult SearchNode(string key)
        {
            UserDomain user = _userService.FindByAccount(key);
            NodeDomain node = new NodeDomain();
            ComponentHelper component = new ComponentHelper();
            if (user != null)
            {
                List<NodeDomain> list = component.ListNodeByUser(user.Id, 1).ToList();
                if (list.Count > 0)
                {
                    NodeDomain firstNode = list.First();
                    return Content(firstNode.Id.ToString());
                }
            }
            else 
            {
                NodeDomain result = component.FindNode(long.Parse(key));
                if (result!=null)
                {
                    node = result;
                }
            }
            return Content(node.Id.ToString());
        }
        [HttpPost]
        [ValidateInput(false)]
        public JsonResult CreateNode(NodeDomain node, FormCollection form)
        {
            var nodeModel = new NodeModel(new NodeDomain());
            if (!string.IsNullOrEmpty(form["verifyCode"]) && !VerifyCodeHelper.IsValid(form["verifyCode"]))
            {
                nodeModel.ReturnCode = MessageTypeEnum.GetInstance().Error;
                nodeModel.ReturnMsg = "验证码错误";
                return Json(nodeModel);
            }
            node.SiteId = CoralNodeContext.Current.Site.Id;
            node.PrototypeId = _prototypeAccessService.FindCategory(node.CategoryId).PrototypeId;
            NodeDomain result = _nodeAccessService.CreateNode(node, form);
            if (result.PrototypeId == 2)
            {
                result.Rank = 0;
                result.Update();
            }
            nodeModel = new NodeModel(result);
            nodeModel.ReturnCode = MessageTypeEnum.GetInstance().Success;
            nodeModel.ReturnMsg = "发表成功";
            return Json(nodeModel);
        }
        [HttpPost]
        public JsonResult CreateUserNode(long nodeId, int refType)
        {
            IList<NodeDomain> userNodeList = _userAccessService.ListUserNode(new UserNodeViewSearhQuery()
            {
                UserId = CoralNodeContext.Current.ReceptionUser.Id,
                RefType = refType
            },null,0 );
            NodeDomain node = new NodeDomain();
            if (userNodeList.Count > 0)
            {
                node = userNodeList.ToList().First();    
            }
            if (node.Id > 0)
            {
                UserNodeRelationDomain userNode = _userAccessService.FindUserNode(new UserNodeSearchQuery()
                {
                    UserId = CoralNodeContext.Current.ReceptionUser.Id,
                    NodeId = node.Id,
                    RefType = refType
                });
                userNode.NodeId = nodeId;
                userNode.CreateTime = DateTime.Now;
                userNode.RefType = refType;
                userNode.Update();
                if (userNode.Id != node.Id)
                {
                    node.Delete();
                    return Json(true);
                }
                else
                {
                    return Json(false);
                }
                
            }
            else
            {
                bool result = _userAccessService.CreateUserNode(new UserNodeRelationDomain
                {
                    UserId = CoralNodeContext.Current.ReceptionUser.Id,
                    NodeId = nodeId,
                    RefType = refType
                });
                return Json(result);
            }
        }
    }
}